// 创建库 https://www.w3.org/TR/IndexedDB/
const request = window.indexedDB.open("library");
let db;

request.onupgradeneeded = function () {
  // The database did not previously exist, so create object stores and indexes.
  const db = request.result;
  // 创建数据表
  const store = db.createObjectStore("books", { keyPath: "isbn" });
  const titleIndex = store.createIndex("by_title", "title", { unique: true });
  const authorIndex = store.createIndex("by_author", "author");

  // 添加数据
  store.add({ title: "Quarry Memories", author: "Fred", isbn: 123456 });
  store.add({ title: "Water Buffaloes", author: "Fred", isbn: 234567 });
  store.add({ title: "Bedrock Nights", author: "Barney", isbn: 345678 });
  store.add({ title: "update Nights", author: "update", isbn: 123678 });
  store.add({ title: "delete one1", author: "xxx", isbn: 983763 });
};

request.onsuccess = function () {
  db = request.result;
  // 建立事务
  const tx = db.transaction("books", "readonly");
  const store = tx.objectStore("books");
  const byTitle = store.index("by_title");
  // 查询数据， 搜索一条数据
  const search = byTitle.get("Bedrock Nights");
  search.onsuccess = function () {
    const matching = search.result;
    if (matching !== undefined) {
      // A match was found.
      report("only one", matching.isbn, matching.title, matching.author);
    } else {
      // No match was found.
      report(null);
    }
  };
  // 查询多条数据
  const byAuthor = store.index("by_author");
  const searchMore = byAuthor.openCursor(IDBKeyRange.only("Fred"));
  searchMore.onsuccess = function () {
    const cursor = searchMore.result;
    if (cursor) {
      // Called for each matching record.
      report(
        "more",
        cursor.value.isbn,
        cursor.value.title,
        cursor.value.author
      );
      cursor.continue();
    } else {
      // No more matching records.
      report(null);
    }
  };
  // 创建可以读写的事务
  const rw = db.transaction("books", "readwrite");
  const rwStore = rw.objectStore("books");
  const updateOne = rwStore.index("by_title").get("update Nights");
  const updateBook = {
    title: "updated Nights",
    author: "updated",
    isbn: 123678,
  };
  updateOne.onsuccess = function (e) {
    // matching是查询出的数据
    // const matching = updateOne.result;
    rwStore.put(updateBook);
    console.log("updated successfully");
  };

  rwStore.delete(983763).onsuccess = function (e) {
    console.log("删除成功！");
  };
};

const report = (...rest) => {
  console.log(...rest);
};
